import 'package:flutter/cupertino.dart';
import 'package:get/get.dart';
import '../../../fluttergromore/api/api_service.dart';
import '../../../fluttergromore/config/app_const.dart';
import '../../../fluttergromore/usersp/user_sp.dart';
import '../../../utils/toast_utils.dart';

// 反馈类型数据模型
class FeedbackType {
  final int id;
  final String name;
  final String? icon;

  FeedbackType({required this.id, required this.name, this.icon});

  factory FeedbackType.fromJson(Map<String, dynamic> json) {
    return FeedbackType(
      id: json['id'],
      name: json['name'],
      icon: json['icon'],
    );
  }
}

class FeedbackLogic extends GetxController {
  TextEditingController contentController = TextEditingController();
  TextEditingController contactController = TextEditingController();
  var contentCount = 0.obs;
  
  // 反馈类型列表（默认值，便于离线或接口异常时展示）
  // 默认三项：id 1=功能建议，2=闪退/崩溃，4=其他；icon 统一为空
  var feedbackTypes = <FeedbackType>[
    FeedbackType(id: 1, name: '功能建议', icon: null),
    FeedbackType(id: 2, name: '闪退/崩溃', icon: null),
    FeedbackType(id: 4, name: '其他', icon: null),
  ].obs;
  // 选中的反馈类型
  var selectedTypeId = 1.obs;

  @override
  void onReady() {
    super.onReady();
    contentController.addListener(() {
      contentCount.value = contentController.text.length;
    });
    getVipIssuesList();
  }

  ///提交
  void onTapCommit() async {
    String content = contentController.text;
    String contact = contactController.text;
    if (content.isEmpty) {
      MyToast.show("请输入反馈的问题或建议");
      return;
    }
    if (contact.isEmpty) {
      MyToast.show("请输入联系方式");
      return;
    }

    MyToast.show("感谢您的反馈");
    Get.back();

    try {
      Map<String,String> map = {};
      map["appId"] = AppConst.djAppId;
      map["djId"] = await UserSp.instance.getDjid()??"";
      map["issuesId"] = selectedTypeId.value.toString();
      map["content"] = content;
      if (contact.isNotEmpty) {
        map["contact"] = contact;
      }
      // if (email.isNotEmpty) {
      //   map["email"] = email;
      // }
      var data = await ApiService().afterSalesForm(map);
      // if (data.isSucceed) {
      //   MyToast.show("感谢您的反馈");
      //   Get.back();
      // }else{
      //   MyToast.show(data.message??"反馈失败");
      // }
    } catch (e) {
      debugPrint('获取反馈类型失败: $e');
    }

  }

  //反馈问题列表
  void getVipIssuesList() async{
    try {
      var data = await ApiService().vipIssuesList();
      if (data.isSucceed && data.data != null) {
        List<dynamic> typeList = data.data;
        feedbackTypes.value = typeList.map((item) => FeedbackType.fromJson(item)).toList();
        // 默认选中第一个类型
        if (feedbackTypes.isNotEmpty) {
          selectedTypeId.value = feedbackTypes.first.id;
        }
      }
    } catch (e) {
      debugPrint('获取反馈类型失败: $e');
    }
  }
  
  // 选择反馈类型
  void selectFeedbackType(int typeId) {
    selectedTypeId.value = typeId;
  }
}
